//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.Blogs
{
	/// <summary>
	/// Summary description for ConvertReferralToTrackbackCommand.
	/// </summary>
	public class ConvertReferralToTrackbackCommand : BlogCommand
	{
		public ConvertReferralToTrackbackCommand()
		{
		}

		public override string Message(BlogCommandPage page)
		{
			int postid = CSContext.Current.PostID;
			if(postid > 0)
			{
				WeblogPost wp = WeblogPosts.GetPost(postid,false,false,true);
				if(wp != null)
				{
					return ResourceManager.GetString("CP_Blogs_Referrals_CreateTrackbackConfirmation");
				}
			}
	        
			throw new Exception("The post could not be found");
		}

		public override void Action(BlogCommandPage page)
		{
			CSContext cntx = CSContext.Current;
			int postid = cntx.PostID;
			int referralID = cntx.GetIntFromQueryString("ReferralID", -1);
			if(postid > 0 && referralID > 0)
			{
				Referral _referral = new Referral();
				_referral.SectionID = page.CurrentWeblog.SectionID;
				_referral.PostID = postid;
				ReferralSet rs = CommunityServer.Components.Referrals.GetReferrals(_referral, 99999, 0);
				_referral = null;
				foreach (Referral r in rs.Referrals)
				{
					if (r.ReferralID == referralID)
					{
						_referral = r;
						continue;
					}
				}


				if (_referral != null)
				{
					WeblogPost entry = new WeblogPost();
					entry.BlogPostType = BlogPostType.Trackback;
					entry.SectionID = _referral.SectionID;
					entry.ParentID = postid;
					entry.Subject = _referral.Url;
					entry.TitleUrl = _referral.Url;
					entry.TrackBackName = "TrackBack";
					entry.Body = String.Empty;
					entry.IsApproved = true;
					entry.PostDate = DateTime.Now;
					entry.UserTime = DateTime.Now;
					entry.Username = cntx.UserName;
					entry.User = cntx.User;
					WeblogPosts.Add(entry);
					return;
				}

			}

			throw new Exception("The referral could not be found");
	        
		}

		public override string Title
		{
			get
			{
				return ResourceManager.GetString("CP_Blogs_Referrals_ConvertReferralTitle");
			}
		}

	}
}
